package son.tl;
import java.io.Serializable;
import java.util.logging.Logger;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import javax.persistence.Transient;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceException;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.users.User;

import son.tl.EMF;
import son.tl.UserPrefs;

@SuppressWarnings("serial")
@Entity(name = "UserPrefs")
public class UserPrefs implements Serializable{
	@SuppressWarnings("unused")
	@Transient
	private static Logger logger = Logger.getLogger(UserPrefs.class.getName());

	@Id
	private String userId;
	private int tzOffset;
	@Basic
	private User user;
	public UserPrefs(String userId) {
		this.userId = userId;
	}
	public String getUserId() {
		return userId;
	}
	public int getTzOffset() {
		return tzOffset;
	}
	public void setTzOffset(int tzOffset) {
		this.tzOffset = tzOffset;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}


	public static UserPrefs getPrefsForUser(User myUser) {
		UserPrefs userPrefs = null;
		String cacheKey = "UserPrefs:" + myUser.getUserId();
		try {
			MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
			if (memcache.contains(cacheKey)) {
				userPrefs = (UserPrefs) memcache.get(cacheKey);
				return userPrefs;
			}
			// If the UserPrefs object isn't in memcache,
			// fall through to the datastore.
		} catch (MemcacheServiceException e) {
			// If there is a problem with the cache,
			// fall through to the datastore.
		}
		EntityManager em = EMF.get().createEntityManager();
		try {
			userPrefs = em.find(UserPrefs.class, myUser.getUserId());
			if (userPrefs == null) {
				userPrefs = new UserPrefs(myUser.getUserId());
				userPrefs.setUser(myUser);
			} else {
				try {
					MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
					memcache.put(cacheKey, userPrefs);
					// Ignore cache problems, nothing we can do.
				} catch (MemcacheServiceException e) {
				}
			}
		} finally {
			em.close();
		}
		return userPrefs;
	}

	public void save() {
		EntityManager em = EMF.get().createEntityManager();
		try {
			String cacheKey = "UserPrefs:" + this.getUserId();
			MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
			memcache.put(cacheKey, this);
			em.persist(this);
		} catch(Exception e){
			e.printStackTrace();
		}finally {
			em.close();
		}
	}
}